package cn.edu.ctbu.scoremg.service;

import cn.edu.ctbu.scoremg.constant.REnum;
import cn.edu.ctbu.scoremg.dao.TeacherRepository;
import cn.edu.ctbu.scoremg.entity.Teacher;
import cn.edu.ctbu.scoremg.exception.RException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TeacherService {
    @Autowired
    public TeacherRepository teacherRepository;


    /**
     * 读所有教师列表
     * @return List Teacher
     *
     */
    public List<Teacher> findALL(){
        return teacherRepository.findAll();
    }

    public Page<Teacher> getAll(Pageable pageable){
        return teacherRepository.findAll(pageable);
    }

    public Page<Teacher> getAll(Example<Teacher> example, Pageable pageable){
        return teacherRepository.findAll(example,pageable);
    }


    /**
     * 按id进行查询
     * @param id 主键，自增
     * @return
     */
    public Teacher findById(Integer id){
        return teacherRepository.findById(id).get();
    }

    /**
     * 按姓名进行查询
     * @param name
     * @return
     */
    public List<Teacher> findByNameLike(String name){
        return teacherRepository.findByNameLike(name);
    }

    /**
     *按名字和学号进行查询
     * @param name
     * @param tno
     * @return
     */
    public List<Teacher> findByNameAndTno(String name,String tno){
        return teacherRepository.findByNameAndTno(name,tno);
    }

    /**新增*/
    public Teacher insert(Teacher teacher){
        return teacherRepository.save(teacher);
    }

    /**更新*/
    public Teacher update(Teacher teacher){
        return teacherRepository.save(teacher);
    }

    /**根据id删除*/
    public void delete(Integer id){
       teacherRepository.deleteById(id);
    }


    /**根据id批量删除*/
    @Transactional
    public void deleteByIds(List<Integer> ids){

            teacherRepository.deleteByIds(ids);

    }

    public List<Teacher> findByTno(String tno){
         return teacherRepository.findByTno(tno);
    }

    /*验证用户名和密码*/
    public Teacher validateUsernameAndPassword(String tno, String password) throws Exception{
        List<Teacher> teachers = teacherRepository.findByTno(tno);
        if(teachers.size() > 0){
            //可能对password加密，但我们暂时不做处理
            Teacher teacher = teachers.get(0);
            if(teacher.getPassword().equals(password)){
                //成功
                return teacher;
            }else {
                throw new RException(REnum.LOGIN_ERR);
            }
        }else {
            throw new RException(REnum.LOGIN_ERR);
        }
    }

}
